package com.hqyj.javaSpringBoot.config.shiro;

import com.hqyj.javaSpringBoot.modules.account.entity.Resource;
import com.hqyj.javaSpringBoot.modules.account.entity.Role;
import com.hqyj.javaSpringBoot.modules.account.entity.User;
import com.hqyj.javaSpringBoot.modules.account.service.ResourceService;
import com.hqyj.javaSpringBoot.modules.account.service.RoleService;
import com.hqyj.javaSpringBoot.modules.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    /**
     * - 资源授权器
     * - 将当前用户对应的角色信息，以及角色所拥有的资源信息放入验证器
     * - 通过前端页面 shiro 标签、控制器方法 shiro 注解与验证器比对，
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();


        User user = (User)principalCollection.getPrimaryPrincipal();

        List<Role> roles = roleService.getRolesByUserId(user.getId());
        roles.stream().forEach(role -> {
            simpleAuthorizationInfo.addRole(role.getRoleName());
            List<Resource> resources=resourceService.getResourceByRoleID(role.getId());
            resources.stream().forEach(resource -> {
                simpleAuthorizationInfo.addStringPermission(resource.getPerssion());
            });
        });

        return simpleAuthorizationInfo;
    }

    /**
     * 身份验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        /**
         * principal: 当前用户信息，可以是user对象，也可以是用户名
         * credentials: 当前用户凭证
         * realmName: 当前 realm 对象的唯一名字
         */
        String userName =(String) token.getPrincipal();
        User user = userService.getUserByUserName(userName);
        if (user==null){
            throw new UnknownAccountException("the account do no exist");
        }

        /**
         * SimpleAuthenticationInfo实现了AuthenticationInfo接口
         */
        return new  SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
